<?php
define('CRMURL', 'http://localhost:8000');
define('LOGPATH','C:\\crm\\CRM\\static\\log\\');
define('WEB_ROOT','C:\\crm\\wamp\\www\\');
define('RAND_UNIQ',rand(11111,99999));

function doGroupSending($maillist , $subject , $content,$send_id,$sendgroup=1,$delaytime=0, $minms=0 , $maxms=0 , $sendn=0 , $stopm=0){
	writelog('准备发送邮件');
	if(count($maillist)<1 || empty($subject) || empty($content)){
		exit(writelog('邮件内容、object或fromEmail存在空值，退出程序',__FILE__,__LINE__));
	}
	require_once WEB_ROOT.'phpmail/class.phpmailer.php';
	try{
		$error = ''; //记录错误信息，用于写log
		$upd_sender_sql = array(); //最后用于更新from email的发送数量
		
		//获取fromemail
		$today = date('Y-m-d',time());
		$sql = "select `emailadd` email,`emailpwd` pwd,`emailname` name,`smtp_server` smtp,`daytimes`,`daylimit` from `crm_smtpsendermaillist` where `is_removed`<1 and `status`>0 and `daytimes`<`daylimit` and `group`={$sendgroup}";
		$ret = @mysql_query($sql);
		$sysmails = array();
		$i = 0;
		while($row = mysql_fetch_array($ret)){
				$sysmails[$i]['email'] = $row['email'];
				$sysmails[$i]['pwd'] = $row['pwd'];
				$sysmails[$i]['name'] = $row['name'];
				$sysmails[$i]['daytimes'] = $row['daytimes'];
				$sysmails[$i]['daylimit'] = $row['daylimit'];
				$sysmails[$i++]['smtp'] = $row['smtp'];
		}
		if(count($sysmails)<1){
			writelog('没有符合条件的发件箱,程序结束');
			exit;
		}
		shuffle($sysmails);
		unset($sql,$ret,$row,$i);
		
		$mailcontent = file_get_contents(WEB_ROOT.'phpmail/ajaxmail/mailcontent_tpl.php');
		$content_temp = str_replace(array('{content}','{sendid}','{CRMURL}'),array($content,$send_id,CRMURL), $mailcontent);
		$send_ret = array('suc'=>array(),'fail'=>array());
		$tolsender = count($sysmails);
		
		$mail = new PHPMailer(true); //New instance, with exceptions enabled
		$mail->IsSMTP();                           // tell the class to use SMTP
		$mail->SMTPAuth   = true;                  // enable SMTP authentication
		$mail->SMTPDebug = 0;
		$mail->logPath = LOGPATH;
		$mail->WordWrap   = 80; // set word wrap
		//$mail->ConfirmReadingTo= 'test';
		$mail->IsHTML(true); // send as HTML
		$i = 0;
		$fail = 0;
		$sendNums = 1;
		$smtp_server_temp = '';
		//foreach ($maillist as $v){
		for($j=0;$j<count($maillist);$j++){
			$v = $maillist[$j];
			if($i>=$tolsender){$i=0;}
			if($tolsender>0){
				if($smtp_server_temp == $sysmails[$i]['smtp']){usleep(rand($minms,$maxms));}  //相同smtp服务商延迟指定时间
				if($sendNums%$sendn==0){usleep($stopm);} //每发送sendn封信，就暂停stopm秒。
				$smtp_server_temp = $sysmails[$i]['smtp']; //记录本次发送的smtp服务器
				$mailname = explode('@',$v['mail']);
				$mail->Username   = $sysmails[$i]['email'];     // SMTP server username
				$mail->Password   = $sysmails[$i]['pwd'];            // SMTP server password
				$mail->Subject  = 'HI '.$mailname[0].'! '.$subject;
				if(!checkEmail($v['mail'])){
					$sql = 'insert into `crm_smtpmaillog` values("","'.$v['mail'].'","'.$v['name'].'",1,"'.$send_id.'","'.$mail->Username.'","The email is invalid!",0)';
					$upd1 = 'update `crm_smtpsendmalilist` set `send_state`=1 where `send_state`>1 and `mail_sendmail`="'.$v['mail'].'"';
					$upd2 = 'update `crm_members` set `email_state`=0 where `email_state`>0 and `email`="'.$v['mail'].'"';
					@mysql_query($sql);
					@mysql_query($upd1);
					@mysql_query($upd2);
					writelog('Invalid Email :'.$v['mail'],__FILE__,__LINE__);
					continue;
				}
				$content = 'HI '.$mailname[0].':<br>'.str_replace('{email}', $v['mail'], $content_temp);
			
				$mail->ClearAllRecipients();
				$mail->ClearReplyTos();
				$mail->MsgHTML($content);
				$mail->AltBody    =  $content;//邮件内容
				$mail->Host       = $sysmails[$i]['smtp']; // SMTP server
				if($sysmails[$i]['smtp'] == 'smtp.gmail.com'){ //gmail 使用了ssl 以及 465端口
					$mail->SMTPSecure = "ssl";
					$mail->Port       = 465;
				}else{
					$mail->Port       = 25;
				}
				//$mail->IsSendmail();  // tell the class to use Sendmail
				$mail->AddReplyTo($sysmails[$i]['email'],$sysmails[$i]['name']);
				$mail->From       = $sysmails[$i]['email'];
				$mail->FromName   = $sysmails[$i]['name'];
				try {
					$mail->AddAddress($v['mail']);
					$mail->Send();
					$sql = 'insert into `crm_smtpmaillog` values("","'.$v['mail'].'","'.$v['name'].'",2,"'.$send_id.'","'.$mail->Username.'","",0)';
					$upd1 = 'update `crm_smtpsendmalilist` set `send_state`=2 where `mail_sendmail`="'.$v['mail'].'"';
					$upd2 = 'update `crm_members` set `email_state`=1 where `email`="'.$v['mail'].'"';
					@mysql_query($sql);
					@mysql_query($upd1);
					@mysql_query($upd2);
					//$send_ret['suc'][]=$v['mail'];
					$upd_sender_sql[$mail->Username] = isset($upd_sender_sql[$mail->Username])?$upd_sender_sql[$mail->Username] + 1:1;
					if(($upd_sender_sql[$mail->Username] + $sysmails[$i]['daytimes'])>=$sysmails[$i]['daylimit']){ //在发送过程中如果当日发送量达到限制数量则停止该FromMail发送
						unset($sysmails[$i]);
						$tolsender=count($sysmails);
					}
				}catch (phpmailerException $e){
					if($e->getCode()==1001){ //接收邮件不存在
						$sql = 'insert into `crm_smtpmaillog` values("","'.$v['mail'].'","'.$v['name'].'",1,"'.$send_id.'","'.$mail->Username.'","'.$e->getMessage().'",0)';
						$upd1 = 'update `crm_smtpsendmalilist` set `send_state`=1 where `send_state`>1 and `mail_sendmail`="'.$v['mail'].'"';
						$upd2 = 'update `crm_members` set `email_state`=0 where `email_state`>0 and `email`="'.$v['mail'].'"';
						@mysql_query($sql);
						@mysql_query($upd1);
						@mysql_query($upd2);
						$upd_sender_sql[$mail->Username] = isset($upd_sender_sql[$mail->Username])?$upd_sender_sql[$mail->Username] + 1:1;
						if(($upd_sender_sql[$mail->Username] + $sysmails[$i]['daytimes'])>=$sysmails[$i]['daylimit']){ //在发送过程中如果当日发送量达到限制数量则停止该FromMail发送
							unset($sysmails[$i]);
							$tolsender=count($sysmails);
						}
						writelog($e->getMessage().'- Send Fail!',__FILE__,__LINE__);
					}else{ //fromEmail 有问题
						$sql1 = 'insert into `crm_smtpmaillog` values("","'.$v['mail'].'","'.$v['name'].'",0,"'.$send_id.'","'.$mail->Username.'","'.$e->getMessage().'",0)';
						@mysql_query($sql1) or die(writelog('SQL INSERT ERROR~'.':'.$sql1,__FILE__,__LINE__));
						//$j--;//fromEmail无效时，将重新发送
						if($e->getCode()==1002){
							$sql = 'update `crm_smtpsendermaillist` set `status`=0 where `emailadd`=\''.$sysmails[$i]['email'].'\'';
							@mysql_query($sql);
						}else{
							//var_dump($e->getMessage());
							writelog($e->getMessage().':'.$sysmails[$i]['email'],__FILE__,__LINE__);
						}

						$j--;//fromEmail无效时，将重新发送
						//writelog($sysmails[$i]['email'].'-'.$e->getMessage().'-'.$v['mail'].' Send Fail!',__FILE__,__LINE__);
						unset($sysmails[$i]);
						$tolsender=count($sysmails);
					}
					$send_ret['fail'][$fail]['email']=$v['mail'];
					$send_ret['fail'][$fail++]['reason']=$e->getMessage();
				}
				//writelog($mail->AltBody);
				$i++;
				$sendNums++;
			}else{
				$sql1 = 'insert into `crm_smtpmaillog` values("","'.$v['mail'].'","'.$v['name'].'",0,"'.$send_id.'","'.$mail->Username.'","No Valid SenderMail!",0)';
				@mysql_query($sql1);
				//writelog('No Valid SenderMail! '.$v['mail'].' send Fail! ',__FILE__,__LINE__);
				$send_ret['fail'][$fail]['email']=$v['mail'];
				$send_ret['fail'][$fail++]['reason']='No Valid SenderMail! '.$v['mail'].' send Fail! ';
			}
		}
		updateSender($upd_sender_sql);
		writelog('邮件发送完毕，详细情况看发送详情，返回串'.retjson(1,$send_ret),__FILE__,__LINE__);
		exit;
		//return retjson(1,$send_ret);
		//if(isset($error)&&!empty($error))echo '失败邮件:'.trim($error,',').'<br>';
	}catch(Exception $e){
		writelog($e,__FILE__,__LINE__);
		exit;
		//return retjson(0,$e->getMessage());
	}
}

function updateSender($update_sql){
	$sql = "select `emailadd` email,`senddate` date from `crm_smtpsendermaillist` where `is_removed`<1";
	$ret = @mysql_query($sql);
	$sysmail = array();
	while($row = mysql_fetch_array($ret)){
		$sysmail[$row['email']] = $row['date']; 
	}
	$taday = date('Y-m-d',time());
	$sql = '';
	foreach ($update_sql as $k=>$v){
		if($sysmail[$k]!=$taday){
			$sql = 'update `crm_smtpsendermaillist` set `senddate`=now(),`daytimes`='.$v.',`sendtimes`=`sendtimes`+'.$v.' where `emailadd`=\''.$k.'\'';
		}else{
			$sql = 'update `crm_smtpsendermaillist` set `daytimes`=`daytimes`+'.$v.',`sendtimes`=`sendtimes`+'.$v.' where `emailadd`=\''.$k.'\'';
		}
		@mysql_query($sql);
	}
}
/**
 * @name:auto_create_folder
 * @param:
 * $filepath: 需要创建的文件夹路径或者文件名
 * $mod: 创建文件夹的权限值
 * @return true or false
 * @author: 黄志勇 hzy@51094.com
 * @link: http://www.51094.com
 */
function auto_create_folder($filepath,$mod=777){
	$abcpath = ($filepath==end(explode('.',$filepath)))?$filepath:dirname($filepath);
	if(is_file($filepath) || is_dir($abcpath))return true;
	try{
		$dirname = dirname($abcpath);
		if(!is_dir($dirname) && $dirname != $abcpath){
			auto_create_folder($dirname);
		}
		mkdir($abcpath,$mod);
		return true;
	}catch(Exception $e){
		return false;
	}
}

function writelog($msg,$file='',$line=''){
	$year = date('Y',time());
	$month = date('m',time());
	$today = date('Ymd',time());
	$datetime = date('Y-m-d H:i:s',time());
	if(!empty($file)){
		$file = ' File:'.$file;
	}
	if(!empty($line)){
		$line = ' Line:'.$line;
	}
	$msg = "[".RAND_UNIQ."][$datetime][SendMail]-".$msg.$file.$line;
	$logpath = LOGPATH.$year.'\\'.$month.'\\'.$today.'.log';
	auto_create_folder($logpath);
	$f = fopen($logpath, 'a+');
	fputs($f,$msg."\r\n");
	fclose($f);
}

function getRequest($sVar,$sRef=NULL){
	return isset($_REQUEST[$sVar]) ? $_REQUEST[$sVar] : $sRef;
}

function retjson($code=1,$msg=array('suc'=>'','fail'=>''),$callback=null){
	$retarr = array('code'=>$code,'msg'=>$msg);
	if(empty($callback))return json_encode($retarr);
	return $callback.'('.json_encode($retarr).')'	;
}

/*
 *  函数名：uploadFlie()
*  作     用：处理文件上传
*  返回值：成功：返回新文件名称 ;  失败：返回false
*  参     数：
*    @ $fileName ：字符  从表单中提交过来的File类型的表单名称
*    @ $storePath：字符  文件存储的最终位置
*    @ $fileType ：数组  文件上传的类型限制
*    @ $maxSize	：数字  文件上传的最大尺寸,默认最大为1024K
*  创建日期：2011-09-05
*  创建人:黄志勇
*/
function uploadFlie($fileName,$storePath,$fileType=array('jpg','jpeg'),$maxSize=2048){
	$fileinfo = $_FILES[$fileName];
	if($fileinfo['error']==4)return false; //文件不存在时返回
	$type = explode('/',$fileinfo['type']);
	if($type[0] == 'image'){
		$photoinfo = getimagesize($fileinfo['tmp_name']);
		$photo_width = $photoinfo[3]['width'];
		$photo_height = $photoinfo[3]['height'];
		if($photo_width > $photo_height){
			exit('照片的尺寸为200*250，大小为'.$maxSize.'Kb');
		}
	}
	if ($fileinfo['error']>0){
		$error = '';
		$consize = ini_get('upload_max_filesize');
		switch ($fileinfo['error']){
			case 1:$error = "上传文件太大，不予上传!最大限制为".$consize;break;//上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值
			case 2:$error = "上传文件太大，不予上传!最大限制为".$consize;break;//上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值
			case 3:$error = "文件上传不完整，请再试一次!";break;//文件只有部分被上传
			case 4:$error = "上传文件不能为空";break;//没有文件被上传
			default:$error = "系统繁忙，请稍后再试!";
		}
		exit($error);
	}
	if(is_array($fileType) && !in_array(trim($type[1]),$fileType)){
		$str = '';
		foreach ($fileType as $v){
			$str .= $v.',';
		}
		$str = trim($str,',');
		exit("上传的文件类型必须为".$str);
	}
	if($fileinfo['size'] == 0){
		exit('上传文件大小不能为0，请重试!');
	}
	if($fileinfo['size'] > $maxSize*1024){
		exit('上传的文件最大为 '.$maxSize.'Kb，请减小文件的大小后重试!');
	}
	return move_uploaded_file($fileinfo['tmp_name'],$storePath);
}
/**
 * 检测电子邮件格式合法性
 * @author wubingjie
 * @param mixed $str	待检测字符串
 * @return bool
 */
function checkEmail( $str )
{
	if( preg_match('/^[\w\.-]+?@[\w-]+?(\.\w{1,4}){1,3}$/',$str) )
	{
		return true;
	}
	else
	{
		return false;
	}
}
/*是否是AJAX请求*/
function isAjax()
{
	return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
	strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == "xmlhttprequest";
}
